package com.dwjm.shop.order;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/order")
public class ShopOrderHandler extends HttpServlet {
    private ShopOrderDao orderDao = new ShopOrderDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String action = req.getParameter("action");
        String userId = req.getParameter("cid");

        try {
            if("create".equals(action)) {
                handleCreateOrder(req, resp, userId);
            } else if("update".equals(action)) {
                handleUpdateOrder(req, resp);
            }
        } catch (Exception e) {
            sendError(resp, "操作失败: " + e.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("cid");
        List<ShopOrder> orders = orderDao.findOrdersByUserId(Long.valueOf(userId));

        resp.setContentType("application/json;charset=UTF-8");
        new Gson().toJson(orders, resp.getWriter());
    }

    private void handleCreateOrder(HttpServletRequest req, HttpServletResponse resp, String userId)
            throws IOException
    {
        ShopOrder order = new ShopOrder();
        order.setGid(Long.valueOf(req.getParameter("gid")));
        order.setTitle(req.getParameter("title"));
        order.setPrice(Double.valueOf(req.getParameter("price")));
        order.setCid(Long.valueOf(userId));
        order.setState(0L); // 初始状态

        boolean success = orderDao.createOrder(order);
        sendResult(resp, success);
    }

    private void handleUpdateOrder(HttpServletRequest req, HttpServletResponse resp)
            throws IOException
    {
        Long orderId = Long.parseLong(req.getParameter("orderId"));
        String newState = req.getParameter("newState");

        boolean success = orderDao.updateOrderState(orderId, newState);
        sendResult(resp, success);
    }
    private void sendResult(HttpServletResponse resp, boolean success) throws IOException {
        JsonObject result = new JsonObject();
        result.addProperty("success", success);
        resp.getWriter().write(result.toString());
    }

    private void sendError(HttpServletResponse resp, String message) throws IOException {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JsonObject error = new JsonObject();
        error.addProperty("error", message);
        resp.getWriter().write(error.toString());
    }

}
